package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"userCRUD/controllers"
	"userCRUD/utils"
)

var token = ""

func GetToken(c *gin.Context) {
	// 从请求头中获取Token, 没有token就直接返回
	token = c.GetHeader(utils.TokenHeader)
	if token == utils.TokenEmpty {
		c.Next()
	}
}

// AuthToken 登录验证
func AuthToken(c *gin.Context) {
	token = c.GetHeader(utils.TokenHeader)
	if token == utils.TokenEmpty {
		zap.L().Info("[middleware token AuthToken] token is not exist ")
		controllers.ResponseError(c, controllers.ErrorNotLogin)
		c.Abort()
		return
	}
	flag, userId := utils.JwtVerify(token)
	if flag == -1 {
		zap.L().Info("[middleware token AuthToken] token verify failed ")
		controllers.ResponseError(c, controllers.ErrorNotLogin)
		c.Abort()
		return
	}
	c.Set(utils.KeyUserId, userId)
	c.Next()
}

func AuthAdmin(c *gin.Context) {
	value, exist := c.Get(utils.KeyUserRole)
	if !exist {
		zap.L().Warn("[middleware token AuthAdmin] get user_role error ")
		controllers.ResponseError(c, controllers.ErrorNotLogin)
		c.Abort()
		return
	}

	userRole, ok := value.(int)
	if !ok {
		zap.L().Warn("[middleware token AuthAdmin] get user error ")
		controllers.ResponseError(c, controllers.ErrorNotLogin)
		c.Abort()
		return
	}

	if userRole != utils.RoleAdmin {
		zap.L().Warn("[middleware token AuthAdmin] auth user role is not admin ")
		controllers.ResponseError(c, controllers.ErrorNoAuth)
		c.Abort()
		return
	}

	c.Next()
}
